package com.lollipop.programming.thread.sequential;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author Lollipop
 * @Version 1.0
 * @Date 2025/4/14 9:31
 * @Description 有 T1、T2、T3 三个线程，怎么保证 T2 在 T1 执行完后执行，T3 在 T2 执行完后执行 - 使用wait/notify（容易死锁，慎用！！！）
 */
@Slf4j
public class ThreadWaitNotify {
    private static final Object lock = new Object();
    // 判断条件 - 不需要加volatile关键字，因为 synchronized 已经保证可见性和有序性
    private static boolean t1Done = false;
    private static boolean t2Done = false;

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                // T1执行
                log.info("T1执行");
                t1Done = true;
                // 通知T2执行
                lock.notifyAll();
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                while (!t1Done) {
                    try {
                        // 等待 T1 完成
                        lock.wait();
                    } catch (InterruptedException e) {
                        log.error("T2执行异常:{}", e.getMessage());
                    }
                }
                log.info("T2执行");
                t2Done = true;
                // 唤醒 T3
                lock.notifyAll();
            }
        });

        Thread t3 = new Thread(() -> {
            synchronized (lock) {
                while (!t2Done) {
                    try {
                        // 等待 T2 完成
                        lock.wait();
                    } catch (InterruptedException e) {
                        log.error("T3执行异常:{}", e.getMessage());
                    }
                }
                log.info("T3执行");
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
